package com.yitongmao.core.network.service;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.yitongmao.common.CallBackListener;
import com.yitongmao.common.FileUtils;
import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.api.ApiGenerator;
import com.yitongmao.core.network.api.BaseApiInterface;
import com.yitongmao.util.Loger;
import com.yitongmao.util.ToastUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class BaseService {

    private volatile static BaseService instance;

    public ACache mCache;
    BaseApiInterface baseApiInterface;
    private WeakReference<HashMap<String, Call>> mapWeakReference;
    private HashMap<String, Call> callHashMap = new HashMap<String, Call>();

    private BaseService() {
        mCache = ACache.get(ReaderApplication.applicationContext);
        baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        mapWeakReference = new WeakReference<HashMap<String, Call>>(callHashMap);
    }
    public static BaseService getInstance() {
        if (instance == null) {
            synchronized (BaseService.class) {
                if (instance == null) {
                    instance = new BaseService();
                }
            }
        }
        return instance;
    }
    /**
     * 简单get请求，缓存和其它逻辑交给前边处理
     * @param urlParams(在p中生成)，将参数组装成String
     * @param callBackListener              回调，可以p直接实现CallBackListener或者new CallBackListener
     */
    public Call simpleGetRequest(final String urlParams, final CallBackListener callBackListener) {
        if (callBackListener != null) {
            callBackListener.onStart();
        }
        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        Call call = baseApiInterface.simpleGetMethod(urlParams);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response != null && response.isSuccess()) {
                    if (response.body() != null && response.body().toString() != null) {
                        if (callBackListener != null) {
                            callBackListener.onSuccess(response.body().toString());
                        }
                    } else {
                        if (callBackListener != null) {
                            callBackListener.onFail("no return value : " + response.errorBody());
                        }
                    }
                } else {
                    if (callBackListener != null) {
                        callBackListener.onFail(response.errorBody().toString());
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (callBackListener != null) {
                    callBackListener.onFail(t.toString());
                }
            }
        });
        callHashMap.put(urlParams, call);
        return call;
    }

    /**
     * 简单post请求，缓存或其它逻辑交付前方P处理
     * @param url                     地址
     * @param params(在p中生成)，HashMap方式
     * @param callBackListener        回调，可以p直接实现CallBackListener或者new CallBackListener
     */
    public Call simplePostRequest(final String url, Map params, final CallBackListener callBackListener) {
        if (callBackListener != null) {
            callBackListener.onStart();
        }
        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        Call call = baseApiInterface.PostMethodMemBer(url, params);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response != null && response.isSuccess()) {
                    if (response.body() != null && response.body().toString() != null) {
                        if (callBackListener != null) {
                            callBackListener.onSuccess(response.body().toString());
                        }
                    } else {
                        if (callBackListener != null) {
                            callBackListener.onFail("no return value : " + response.errorBody().toString());
                        }
                    }
                } else {
                    if (callBackListener != null) {
                        callBackListener.onFail("no return value : " + response.errorBody().toString());
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (callBackListener != null) {
                    callBackListener.onFail(t.toString());
                }
            }
        });
        return call;

        //callHashMap.put(urlParams,call);
    }

    /**
     * 简单post请求，缓存或其它逻辑交付前方P处理
     *
     * @param url                     地址
     * @param params(在p中生成)，HashMap方式
     * @param callBackListener        回调，可以p直接实现CallBackListener或者new CallBackListener
     */
    public Call simplePostRequestNoHead(final String url, HashMap params, final CallBackListener callBackListener) {
        if (callBackListener != null) {
            callBackListener.onStart();
        }
        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        Call call = baseApiInterface.customPostMethodNoHead(url, params);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response != null && response.isSuccess()) {
                    if (response.body() != null && response.body().toString() != null) {
                        if (callBackListener != null) {
                            callBackListener.onSuccess(response.body().toString());
                        }
                    } else {
                        if (callBackListener != null) {
                            callBackListener.onFail("no return value : " + response.errorBody().toString());
                        }
                    }
                } else {
                    if (callBackListener != null) {
                        callBackListener.onFail("no return value : " + response.errorBody().toString());
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (callBackListener != null) {
                    callBackListener.onFail(t.toString());
                }
            }
        });
        return call;
        //callHashMap.put(urlParams,call);
    }

//    /**
//     * 简单post请求，缓存或其它逻辑交付前方P处理
//     *
//     * @param url                     地址
//     * @param params(在p中生成)，HashMap方式
//     * @param callBackListener        回调，可以p直接实现CallBackListener或者new CallBackListener
//     */
//    public Call simplePostBodyBean(final String url, BaoliaoPostBean params, final CallBackListener callBackListener) {
//        if (callBackListener != null) {
//            callBackListener.onStart();
//        }
//        if (baseApiInterface == null) {
//            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
//        }
//        Call call = baseApiInterface.customPostMethodBean(url, params);
//        call.enqueue(new Callback() {
//            @Override
//            public void onResponse(Call call, Response response) {
//                if (response != null && response.isSuccess()) {
//                    if (response.body() != null && response.body().toString() != null) {
//                        if (callBackListener != null) {
//                            callBackListener.onSuccess(response.body().toString());
//                        }
//                    } else {
//                        if (callBackListener != null) {
//                            callBackListener.onFail("no return value : " + response.errorBody().toString());
//                        }
//                    }
//                } else {
//                    if (callBackListener != null) {
//                        callBackListener.onFail("no return value : " + response.errorBody().toString());
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Call call, Throwable t) {
//                if (callBackListener != null) {
//                    callBackListener.onFail(t.toString());
//                }
//            }
//        });
//        return call;
//        //callHashMap.put(urlParams,call);
//    }

    /**
     * 下载文件
     *
     * @param url              文件地址
     * @param fileName         保存文件名称
     * @param fileFolder       保存到目录
     * @param storePlace       保存到app缓存下或sdcard下 1为手机app下，其它为保存sdcard下
     * @param callBackListener
     */
    public void simpleDownFile(final String url, final String fileName, final String fileFolder, final int storePlace, final CallBackListener callBackListener) {
        if (callBackListener != null) {
            callBackListener.onStart();
        }
        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                if (response != null && response.body() != null && response.body().byteStream() != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //String folderName, String fileName, InputStream inputStream, int storePlace) {
                            boolean success = FileUtils.writeFile(ReaderApplication.getInstace(), fileFolder, fileName, response.body().byteStream(), storePlace);
                            if (success) {
                                if (callBackListener != null) {
                                    callBackListener.onSuccess(success);
                                }
                            } else {
                                if (callBackListener != null) {
                                    callBackListener.onFail("save file failed");
                                }
                            }
                        }
                    }).start();
                } else {
                    if (callBackListener != null) {
                        callBackListener.onFail("no return value : " + response.errorBody());
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (callBackListener != null) {
                    callBackListener.onFail(t.toString());
                }
            }
        });

        callHashMap.put(url, call);
    }
    public void downloadFile(String url, final String fileName, final CallBackListener callBackListener) {
        Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                Loger.i("downloadFile", "downloadFile-onResponse-" + response.body().byteStream());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File file = FileUtils.write2SDFromInput(fileName, response.body().byteStream());
                        Loger.i("downloadFile", "-downloadFile-" + file.getAbsolutePath());
                        if (file.exists()) {
                            Loger.i("downloadFile", "-downloadFile-0");
                            callBackListener.onSuccess(file.getPath());
                        } else {
                            Loger.i("downloadFile", "-downloadFile-1");
                            callBackListener.onFail(response.errorBody());
                        }
                    }
                }).start();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBackListener.onFail(t.toString());
            }
        });
    }

    public void downloadNewVersionFile(String url, final String fileName, final CallBackListener callBackListener) {
        callBackListener.onStart();
        Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                Loger.i("downloadFile", "downloadFile-onResponse-" + response.body().byteStream());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File file = FileUtils.write2SDFromInput(fileName, response.body().byteStream());
                        Loger.i("downloadFile", "-downloadFile-" + file.getAbsolutePath());
                        if (file.exists()) {
                            Loger.i("downloadFile", "-downloadFile-0");
                            callBackListener.onSuccess(file.getPath());
                        } else {
                            Loger.i("downloadFile", "-downloadFile-1");
                            callBackListener.onFail(response.errorBody());
                        }
                    }
                }).start();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBackListener.onFail(t.toString());
            }
        });
    }

    public void downloadImagesFile(String url, final String fileName, final CallBackListener callBackListener) {
        if (FileUtils.ExistSDCard()) {
            callBackListener.onStart();
            Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
            call.enqueue(new Callback<ResponseBody>() {//后台刚才报错了  null
                @Override
                public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                    Loger.i("downloadFile", "downloadFile-onResponse-" + response.body().byteStream());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = FileUtils.writeImages2SDFromInput(fileName, response.body().byteStream());
                            Loger.i("downloadFile", "-downloadFile-" + file.getAbsolutePath());
                            if (file.exists()) {
                                Loger.i("downloadFile", "-downloadFile-0");
                                callBackListener.onSuccess(file.getPath());
                            } else {
                                Loger.i("downloadFile", "-downloadFile-1");
                                callBackListener.onFail(response.errorBody());
                            }
                        }
                    }).start();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callBackListener.onFail(t.toString());
                }
            });
        }else {
            ToastUtils.showShort(ReaderApplication.getInstace(),"下载失败，没有SD卡，请插入SD卡");
        }
    }

    public void downloadSplashImageFiles(String url, final String fileName, final CallBackListener callBackListener) {
        Call<ResponseBody> call = baseApiInterface.downloadGetMethod(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                Loger.i("downloadFile", "downloadFile-onResponse-" + response.body().byteStream());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap splashBitmap = BitmapFactory.decodeStream(response.body().byteStream());
                        if (splashBitmap != null && !splashBitmap.isRecycled()) {
                            //缓存保存一天
                            mCache.put(fileName, splashBitmap, 86400);
                            callBackListener.onSuccess(splashBitmap);
//                            splashBitmap.recycle();
                        } else {
                            callBackListener.onFail(response.errorBody());
                        }
//                        File file = FileUtils.writeImages2SDFromInput(fileName, response.body().byteStream());
//                        Loger.i("downloadFile", "-downloadFile-" + file.getAbsolutePath());
//                        if (file.exists()) {
//                            Loger.i("downloadFile", "-downloadFile-0");
//                            callBackListener.onSuccess(file.getPath());
//                        } else {
//                            Loger.i("downloadFile", "-downloadFile-1");
//                            callBackListener.onFail(response.errorBody());
//                        }
                    }
                }).start();
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBackListener.onFail(t.toString());
            }
        });
    }
    /**
     * 上传单个文件
     * @param url
     * @param fileAbsolutePath 文件路径绝对地址
     * @param callBackListener
     */
    public void uploadOneFile(String url, String fileAbsolutePath,String userId, final CallBackListener callBackListener) {
        if (callBackListener != null) {
            callBackListener.onStart();
        }

        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        HashMap<String, RequestBody> map = new HashMap<>();
        File file = new File(fileAbsolutePath);
        if (file.exists()) {
            String filename = file.getName();
           // Log.e("zzz","filename"+filename);
            RequestBody photo = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            //map.put("image" + filename, photo);
            map.put("file\"; filename=\""+filename, photo);
            //Log.e("zzz","photo"+photo.toString());
            //Call call = baseApiInterface.customMultiFileUpload(url, map,userId);
            Call call = baseApiInterface.customMultiFileUpload(url, map,userId);
            //Log.e("zzz","url"+url+"map:"+map+"userId:"+userId);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, final Response<String> response) {
                    if (response != null && response.isSuccess()) {
                        if (callBackListener != null) {
                            callBackListener.onSuccess(response.body());
                        }
                    } else {
                        if (callBackListener != null) {
                            callBackListener.onFail("no return value : " + response.errorBody().toString());
                        }
                    }
                }
                @Override
                public void onFailure(Call call, Throwable t) {
                    if (callBackListener != null) {
                        callBackListener.onFail(t.toString());
                    }
                }
            });
            callHashMap.put(url, call);
        } else {
            callBackListener.onFail("File is not find");
        }
    }
    /**
     * 上传多个文件
     * @param url
     * @param fileAbsolutePathList 文件路径绝对地址list
     * @param callBackListener
     */
    public Call uploadMultipleFile(String url, ArrayList<String> fileAbsolutePathList, final CallBackListener callBackListener) {
        Call call = null;
        if (callBackListener != null) {
            callBackListener.onStart();
        }
        if (baseApiInterface == null) {
            baseApiInterface = ApiGenerator.createApiClient(BaseApiInterface.class);
        }
        HashMap<String, RequestBody> map = new HashMap<>();
        for (String fileAbsolutePath : fileAbsolutePathList) {
            File file = new File(fileAbsolutePath);
            if (file.exists()) {
                String filename = file.getName();
                RequestBody photo = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                map.put("file\"; filename=\"" + filename, photo);
            }
        }

        if (map.size() > 0) {
            call = baseApiInterface.customMultiFileUpload(url, map);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, final Response<String> response) {
                    if (response != null && response.isSuccess()) {
                        if (callBackListener != null) {
                            callBackListener.onSuccess(response.body());
                        }
                    } else {
                        if (callBackListener != null) {
                            callBackListener.onFail("no return value : " + response.errorBody());
                        }
                    }

                }

                @Override
                public void onFailure(Call call, Throwable t) {
                    if (callBackListener != null) {
                        callBackListener.onFail(t.toString());
                    }
                }
            });
            callHashMap.put(url, call);
        } else {
            if (callBackListener != null) {
                callBackListener.onFail("list files not exists");
            }
        }
        return call;
    }


    public void cancleRequest(String url) {
        Call call = callHashMap.get(url);
        try {
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        } catch (Exception e) {

        }
    }


}
